package javaStu.lockStudy;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: leiwenkang
 * @date: 2020/5/4
 * @time: 12:38
 */
@Slf4j
public class SynchronizedTest {
    private static AtomicInteger executeCount = new AtomicInteger();
    private static AtomicBoolean hadStart = new AtomicBoolean();

    //保证在同一个TM中只加载一次
    public static synchronized void init() {
        System.out.println("AtomicInteger SynchronizedTest: " + executeCount.incrementAndGet() + ", hadStart: " + hadStart.get());
        if (!hadStart.getAndSet(true)) {
            try {
                Thread.sleep(5000);
            } catch (Exception e) {

            }
        }
        System.out.println(Thread.currentThread().getName() + "执行完成");
    }

    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " SynchronizedTest1 准备进入");
            SynchronizedTest.init();

        }).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " SynchronizedTest2 准备进入");
            SynchronizedTest.init();
        }).start();

    }
}
